import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,Input, DatePicker, Button, Card,Icon,Row,Col,message,Select,Tag,Tooltip
} from 'antd';

import moment from 'moment';
import docCookies from "../../common/DocCookies";
import LotteryWinUserList from '../../components/LotteryUserList/index';
const FormItem = Form.Item;
var uuid = 0;

@connect(state => ({
  lottery: state.lottery,
}))
@Form.create()
export default class CreateNewLottery extends PureComponent {
  state = {
    rsId:docCookies.getItem("rsId"),
    pageNo:1,
    pageSize:5,
    total:0,
    resultBtnTxt:"",
    lotteryId:'',
    startTime: '',
    endTime: '',
    formLoading:false,
    createUserId:docCookies.getItem("userId"),
    showDetail:false,
    detail:true,
    lotteryStatus:true,
    winUserRecord:'',
    lotteryUserList:true,
    drawUserId:docCookies.getItem("userId"),
    cczt:false,  //重抽状态
    peopleCount:'',
    keyWord:'',
    messageFrom:'',
    lastOneHour:'',
    nowDate:'',
    informButton:false,
    addButton:true,
    tags: [],
    inputVisible: false,
    inputValue: '',
    newTagVisible:true,
    informAllButton:true,
    newDataParams:false,
  };

  ////初始化渲染后触发 整个过程只调用一次   showDetail:true 展示详情不可编辑
  componentDidMount() {
    this.setState({
      detail:false,
    })
    const { form , dispatch} = this.props;
    if(this.props.location.query) {
      var record = this.props.location.query.record;
      var winUserRecord = this.props.location.query.winUserRecord;
      const showDetail = this.props.location.query.showDetail;
      if (record) {
        if(record.informStatus == '全部通知'){
          this.setState({
            informAllButton:false,
            informButton:true
          })
        } else if(record.informStatus == '部分通知') {
          this.setState({
            informButton:true
          })
        }
        this.setState({
          keyWord:record.keyWord != '' && typeof(record.keyWord)!="undefined" ?eval(record.keyWord) :[],
          tags:record.keyWord != '' && typeof(record.keyWord)!="undefined" ?eval(record.keyWord):[],
          lotteryId:record.id,
          startTime:moment(record.startTime).format('YYYY/MM/DD h:mm'),
          endTime:moment(record.endTime).format('YYYY/MM/DD h:mm'),
          peopleCount:record.peopleCount,
        })
        if(record.messageFrom == '全部') {
          this.state.messageFrom='';
        } else if(record.messageFrom == '微信') {
          this.state.messageFrom= '0';
        } else{
          this.state.messageFrom= '1';
        }
        if(record.lotteryStatus === '未抽') {
          this.setState({
            lotteryUserList:false,
          })
        } else {
          this.setState({
            cczt:true,
          })
        }
        if(showDetail){
          this.setState({
            detail:true,
            winUserRecord:winUserRecord,
            showDetail:showDetail,
            lotteryStatus:record.lotteryStatus === '未抽'? false: true,
            newTagVisible:false,
          });
        } else {
          this.setState({
            lotteryUserList:false,
            detail:false,
          });
        }
        form.setFields({
          lotteryName: {value: record.lotteryName},
          peopleCount: {value: record.peopleCount},
          createUserName: {value: record.createUserName},
          creatTime: {value: record.creatTime},
          lotteryStatus: {value: record.lotteryStatus},
          drawUserName: {value: record.drawUserName},
          drawTime: {value: record.drawTime},
          // informStatus: {value: record.informStatus},
          spreadExpire: {value: [moment(record.startTime.substr(0,String(record.startTime).length-3)), moment(record.endTime.substr(0,String(record.endTime).length-3))]},
        })
      }
    } else {
      var lastOneHour = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
      var nowDate = new Date();
      this.state.startTime = this.getFormatTime(lastOneHour);
      this.state.endTime = this.getFormatTime(nowDate);
      form.setFields({
        spreadExpire: {value: [moment(lastOneHour), moment(nowDate)]},
      })
    }
  }

  handleSubmit = (cj) => {
    var me = this;
    const { form ,dispatch} = this.props;
    const { startTime ,endTime,lotteryId,rsId,createUserId,peopleCount,keyWord} = this.state;
    const pageNo = 1 ;
    const pageSize = 50;
    this.setState({
      formLoading: true
    })
    //详情界面（不可编辑），抽奖和重抽
    if(this.state.showDetail) {
      console.log('查看界面抽奖或重抽')
      // 需要传递的参数信息
      const params = {
        status:0,
        rsId:this.state.rsId,
        drawUserId:this.state.drawUserId,
        lotteryId:lotteryId,
        startTime:startTime.replace(/-/g,"/"),
        endTime:endTime.replace(/-/g,"/"),
        peopleCount:peopleCount,
        keyWord:this.state.tags.length === 0? '':(this.state.tags).toString(),
        messageFrom:this.state.messageFrom,
        pageNo: pageNo,
        pageSize: pageSize,
      };
      dispatch({
        type: 'lottery/listAndSaveLotteryResult',  //请求的action
        payload:params,
        callback:(data) =>{
          form.setFields({
            lotteryStatus: {value: '已抽'},
          })
          me.setState({
            lotteryUserList:true,
            winUserRecord:data,
            formLoading:false,
            showDetail:true,
            cczt:true,
            informAllButton:true
          })
        }
      });
    } else if (lotteryId != '') {   //编辑后保存或直接抽奖
      if(cj){   //直接抽奖
        console.log('编辑或新增界面的抽奖或重抽')
        // 需要传递的参数信息
        const params = {
          status:0,
          rsId:this.state.rsId,
          drawUserId:this.state.drawUserId,
          lotteryId:lotteryId,
          startTime:startTime.replace(/-/g,"/"),
          endTime:endTime.replace(/-/g,"/"),
          peopleCount:peopleCount,
          keyWord:this.state.tags.length === 0? '':(this.state.tags).toString(),
          messageFrom:this.state.messageFrom,
          pageNo: pageNo,
          pageSize: pageSize,
        };
        dispatch({
          type: 'lottery/listAndSaveLotteryResult',  //请求的action
          payload:params,
          callback:(data) =>{
            form.setFields({
              lotteryStatus: {value: '已抽'},
            })
            me.setState({
              lotteryUserList:true,
              winUserRecord:data,
              formLoading:false,
              showDetail:true,
              cczt:true,
              informAllButton:true
            })
          }
        });
      } else {  //编辑后保存
        console.log('编辑界面保存')
        form.validateFields(
          (err, values) => {
            if (!err) {
              //新增
              if(!lotteryId){
                values.informStatus = 0;
                values.lotteryStatus = 0;
                values.createUserId = createUserId;
                values.rsId = rsId;
              }
              values.id = lotteryId;
              values.messageFrom=this.state.messageFrom;
              values.startTime = startTime.replace(/-/g,"/");
              values.endTime = endTime.replace(/-/g,"/");
              values.keyWord = this.state.tags.length === 0? '':JSON.stringify(this.state.tags);
              delete values.spreadExpire;
              dispatch({
                type: 'lottery/fetchSaveOrUpdateLottery',  //请求的action
                payload:values,
                callback:(res) =>{
                  message.success(res.msg);
                  me.setState({
                    formLoading:false,
                  })
                }
              });
            } else {
              this.setState({
                formLoading: false
              })
            }
          }
        );
      }
    } else {                        //新增或新增保存后再抽奖
      if(cj){
        console.log('新增活动后不保存直接抽奖');
        form.validateFields(
          (err, values) => {
            if (!err) {
              //新增
              values.startTime = startTime.replace(/-/g,"/");
              values.endTime = endTime.replace(/-/g,"/");
              delete values.spreadExpire;
              values.informStatus = 0;
              values.lotteryStatus = 0;
              values.createUserId = createUserId;
              values.rsId = rsId;
              values.id = lotteryId;
              values.messageFrom=this.state.messageFrom;
              values.keyWord = this.state.tags.length === 0? '':JSON.stringify(this.state.tags);
              dispatch({
                type: 'lottery/fetchSaveOrUpdateLottery',  //请求的action
                payload:values,
                callback:(res) =>{
                  const newValues = values;
                  newValues.status = 0;
                  newValues.drawUserId = this.state.drawUserId;
                  newValues.lotteryId = res.data.id;
                  newValues.pageNo = pageNo;
                  newValues.pageSize = pageSize;
                  newValues.keyWord = this.state.tags.length === 0? '':(this.state.tags).toString();
                  dispatch({
                    type: 'lottery/listAndSaveLotteryResult',  //请求的action
                    payload:newValues,
                    callback:(data) =>{
                      me.setState({
                        lotteryId:newValues.lotteryId,
                        lotteryUserList:true,
                        winUserRecord:data,
                        formLoading:false,
                        showDetail:true,
                        cczt:true,
                        peopleCount:newValues.peopleCount,
                        newTagVisible:false,
                        informAllButton:true
                      })
                    }
                  });
                }
              });
            }else {
              this.setState({
                formLoading: false
              })
            }
          }
        );
      } else {  //编辑后保存
        console.log('新增后保存')
        form.validateFields(
          (err, values) => {
            if (!err) {
              //新增
              if(!lotteryId){
                values.informStatus = 0;
                values.lotteryStatus = 0;
                values.createUserId = createUserId;
                values.rsId = rsId;
              }
              values.id = lotteryId;
              values.messageFrom=this.state.messageFrom;
              values.startTime = startTime.replace(/-/g,"/");
              values.endTime = endTime.replace(/-/g,"/");
              values.keyWord = this.state.tags.length === 0? '':JSON.stringify(this.state.tags);
              delete values.spreadExpire;
              dispatch({
                type: 'lottery/fetchSaveOrUpdateLottery',  //请求的action
                payload:values,
                callback:(res) =>{
                  message.success(res.msg);
                  me.setState({
                    lotteryId:res.data.id,
                    peopleCount:values.peopleCount,
                    formLoading:false,
                  })
                }
              });
            } else {
              this.setState({
                formLoading: false
              })
            }
          }
        );
      }
    }
  }

  handleChange(value) {
    var me = this;
    me.setState({
      messageFrom:value
    })
  }

  getFormatTime(date){
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      + " " + date.getHours() + seperator2 + date.getMinutes();
    return currentdate;
  }

  informWinUser() {
    const { dispatch} = this.props;
    var data = this.state.winUserRecord.list;
    var id = new Array();
    data.forEach(function(value,index){
      id.push(value.id);
    });
    const params = {
      id:JSON.stringify(id),
      lotteryId:this.state.lotteryId,
      informStatus:1,
    };
    dispatch({
      type: 'lottery/informWinUser',  //请求的action
      payload:params,
      callback:(data) =>{
        message.success(data.msg);
        this.loadLotteryUserList();
      }
    });
  }

  loadLotteryUserList(){
    var me = this;
    const { dispatch } = this.props;
    const pageNo = this.state.pageNo ;
    const pageSize = this.state.pageSize ;
    // 需要传递的参数信息
    const params = {
      lotteryId:this.state.lotteryId,
      pageNo: pageNo,
      pageSize: 50,
      totalPeople:this.state.winUserRecord.totalPeople,
    };
    dispatch({
      type: 'lottery/listLotteryResultById',  //请求的action
      payload:params,
      callback:(data) =>{
        console.log(data)
        me.setState({
          winUserRecord:data,
          pageNo:data.pageNo,
          pageSize:data.pageSize,
          total:data.total,
          informButton:true,
          informAllButton:false,
          newDataParams:true,
        });
      }
    });
  }

  cancelBack = () => {
    history.go(-1);
  }


  handleSearch = (value) => {
    const {pageNo,pageSize} = this.state;
    this.loadMethod(pageNo,pageSize,value)
  }

  onDataPickChange = (dates, dateStrings) => {
    this.setState({
      startTime: dateStrings[0],
      endTime: dateStrings[1]
    })
  }

  _setInformButton() {
    this.setState({
      informButton:true,
    })
  }


  handleClose = (removedTag) => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);
    this.setState({ tags,newTagVisible: true,keyWord:tags });
  }

  showInput = () => {
    if(this.state.showDetail) {
      return;
    } else {
      this.setState({ inputVisible: true ,newTagVisible:false}, () => this.input.focus());
    }
  }

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  handleInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    let tags = state.tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }
    if(tags.length === 3) {
      this.setState({
        newTagVisible: false,
        inputVisible: false,
        tags,
        inputValue: '',
        keyWord:tags
      });
    } else {
      this.setState({
        tags,
        inputVisible: false,
        inputValue: '',
        newTagVisible:true,
        keyWord:tags
      });
    }
  }

  saveInputRef = input => this.input = input

  _setAllInformStatus(){
    this.setState({
      informAllButton:false
    })
  }

  render() {
    const { tags, inputVisible, inputValue ,newTagVisible} = this.state;
    const { getFieldDecorator  } = this.props.form;
    const {formLoading,showDetail} = this.state;
    const RangePicker = DatePicker.RangePicker;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };


    return (
      <div>
        <Form
          hideRequiredMark
          layout="inline"
          style={{ marginTop: 8 }}
        >
          <Card title="互动抽奖基本信息" >
            <FormItem   label="抽奖标题" style={{marginLeft:70}} >
              {getFieldDecorator('lotteryName', {
                rules: [{
                  required: true,
                  message: '请输入抽奖标题',
                }]
              })(
                <Input placeholder="抽奖标题" disabled={showDetail}  style={{width:230}}/>
              )}
            </FormItem>

            <FormItem  label="消息来源" style={{marginLeft:35}}>
              <Select disabled={showDetail} value={this.state.messageFrom} defaultValue={this.state.messageFrom} style={{width:150}} onChange={this.handleChange.bind(this)}>
                <Select.Option value=""> 全部 </Select.Option>
                <Select.Option value="1"> app </Select.Option>
                <Select.Option value="0"> 微信 </Select.Option>
              </Select>
            </FormItem>

            <FormItem label="抽取人数" style={{marginLeft:65,}}>
              {getFieldDecorator('peopleCount', {
                rules: [{
                  required: true,
                  message: '请输入抽取人数',
                }]
              })(
                <Input placeholder="人数" disabled={showDetail} style={{width:70}}/>
              )}
            </FormItem>

            <FormItem  label="时间设置" style={{marginLeft:50}}>
              {getFieldDecorator('spreadExpire', {
                rules: [{
                  required: true,
                  message: '请选择有效期',
                }],
              })(
                <RangePicker
                  disabled={showDetail}
                  //defaultValue={[moment(new Date(), dateFormat), moment('2015/01/01', dateFormat)]}
                  ranges={{ "今天": [moment(), moment()], '这个月': [moment(), moment().endOf('month')] }}
                  showTime
                  format="YYYY/MM/DD HH:mm"
                  onChange={this.onDataPickChange}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>

            {this.state.detail?
              <FormItem  label="创建时间" style={{marginTop:20,marginLeft:70}}>
                {getFieldDecorator('creatTime')(
                  <Input placeholder="创建时间" disabled={showDetail} style={{width:230}}/>
                )}
              </FormItem>
              :null
            }

            {this.state.detail ?
              <FormItem  label="创建人" style={{marginTop:20,marginLeft:35}}>
                {getFieldDecorator('createUserName', {
                  rules: [{
                    required: true,
                    message: '请输入创建人',
                  }]
                })(
                  <Input placeholder="创建人" disabled={showDetail}  style={{width:180}}/>
                )}
              </FormItem>
              :null
            }



            {this.state.detail?
              <FormItem  label="抽奖状态" style={{marginTop:20,marginLeft:50}}>
                {getFieldDecorator('lotteryStatus')(
                  <Input placeholder="抽奖状态" disabled={showDetail} style={{width:70}}/>
                )}
              </FormItem>
              :null
            }

            {this.state.detail && this.state.lotteryStatus?
              <FormItem  label="抽奖人" style={{marginTop:20,marginLeft:50}}>
                {getFieldDecorator('drawUserName')(
                  <Input placeholder="请输入互动关键字" disabled={showDetail} style={{width:180}}/>
                )}
              </FormItem>
              :null
            }

            {this.state.detail && this.state.lotteryStatus ?
              <FormItem  label="抽奖时间" style={{marginTop:20,marginLeft:20}}>
                {getFieldDecorator('drawTime')(
                  <Input placeholder="请输入互动关键字" disabled={showDetail} style={{width:160}}/>
                )}
              </FormItem>
              :null
            }

            {/*{this.state.detail && this.state.lotteryStatus ?
              <FormItem {...formItemLayout} label="通知状态">
                {getFieldDecorator('informStatus')(
                  <Input placeholder="通知状态" disabled={showDetail} />
                )}
              </FormItem>
              :null
            }*/}
            <div >
              <FormItem label="互动关键字" style={{marginLeft:70,marginTop:20}}/>
              {showDetail?this.state.tags.length === 0?<Input value={'无'} disabled={true} style={{marginTop:20,marginLeft:-20,width:100}}/>:null:null}
              {tags.map((tag, index) => {
                const isLongTag = tag.length > 20;
                const tagElem = (
                  <Tag style={{marginTop:30}} key={tag} closable={showDetail?false:true} afterClose={() => this.handleClose(tag)}>
                    {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                  </Tag>
                );
                return isLongTag ? <Tooltip title={tag} style={{marginTop:20}} key={tag}>{tagElem}</Tooltip> : tagElem;
              })}
              {inputVisible && (
                <Input
                  ref={this.saveInputRef}
                  type="text"
                  size="small"
                  style={{ width: 78 ,marginTop:30}}
                  value={inputValue}
                  onChange={this.handleInputChange}
                  onBlur={this.handleInputConfirm}
                  onPressEnter={this.handleInputConfirm}
                />
              )}

              {
                newTagVisible ? showDetail? null :
                  <Tag
                    onClick={this.showInput}
                    style={{ background: '#fff', borderStyle: 'dashed',marginTop:30 }}
                  >
                    <Icon type="plus"/> 新增
                  </Tag>
                  :null
              }
              {/*{newTagVisible && (*/}
                {/*<Tag*/}
                  {/*onClick={this.showInput}*/}
                  {/*style={{ background: '#fff', borderStyle: 'dashed',marginTop:30 }}*/}
                {/*>*/}
                  {/*<Icon type="plus"/> 新增*/}
                {/*</Tag>*/}
              {/*)}*/}
            </div>

          </Card>

          {this.state.lotteryUserList?
            <FormItem {...formItemLayout}  >
            </FormItem>
            :null
          }

          {this.state.lotteryUserList?
            <Card title="中奖用户列表" style={{marginTop:20}}>
              <Row gutter={16} style={{ marginBottom: '10px' }}>
                <Col className="gutter-row" span={4}>
                </Col>

                <Col className="gutter-row" span={3} style={{ marginLeft:-260 }}>
                  <Button type="primary" disabled={!this.state.informAllButton}
                          onClick={() => this.informWinUser()}>一键通知</Button>
                </Col>
                <Col className="gutter-row" span={3}  style={{ float:'right' }}>
                  <span>符合抽奖条件总人数：{this.state.winUserRecord.totalPeople}</span>
                </Col>

                <Col className="gutter-row" span={4}>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col className="gutter-row" span={4}>
                </Col>
                <Col className="gutter-row" span={26}>
                  <LotteryWinUserList
                    winUserRecord={this.state.winUserRecord.list}
                    showDelBtn = {showDetail}
                    total = {this.state.winUserRecord.total}
                    pageNo = {this.state.winUserRecord.pageNo}
                    pageSize = {this.state.winUserRecord.pageSize}
                    lotteryId = {this.state.lotteryId}
                    dispatch = {this.props.dispatch}
                    informButton={this._setInformButton.bind(this)}
                    allInformStatus={this._setAllInformStatus.bind(this)}
                    newDataParams={this.state.newDataParams}
                  />
                </Col>
                <Col className="gutter-row" span={4}>
                </Col>
              </Row>
            </Card>
            :null
          }


          <FormItem  style={{ marginTop: 20 }}>
            <Row >
              <Col span={24}>
                {showDetail?null:
                  <Button type="primary" htmlType="submit" loading={formLoading} style={{ marginLeft: 600 }}
                          onClick={() => this.handleSubmit()} >保存</Button>}

                <Button type="primary" htmlType="submit" disabled={this.state.informButton} loading={formLoading}
                        style={{ marginLeft: showDetail?700:50 }} onClick={() => this.handleSubmit(true)} >{this.state.cczt?'重抽':'抽奖'}</Button>

                <Button onClick={() => this.cancelBack()} style={{ marginLeft: 50 }}>返回</Button>
              </Col>
            </Row>
          </FormItem>
          {/*<FormItem {...submitFormLayout} style={{ marginTop: 20 }}>*/}
            {/*<Row gutter={16} style={{ marginBottom: '10px' }}>*/}
              {/*<Col className="gutter-row" span={9}>*/}
              {/*</Col>*/}
              {/*<Col className="gutter-row" span={3}>*/}
                {/*{showDetail?*/}
                  {/*this.state.lotteryUserList ? null*/}
                    {/*:<Button onClick={() => this.cancelBack()} style={{ marginLeft: 450 }}>确定</Button>*/}
                  {/*:null*/}
                {/*}*/}

              {/*</Col>*/}
              {/*<Col className="gutter-row" span={9}>*/}
              {/*</Col>*/}
            {/*</Row>*/}
          {/*</FormItem>*/}

          {/*{this.state.lotteryUserList?*/}
            {/*<FormItem style={{ marginTop: 20,marginBottom:20 }}>*/}
              {/*<Row >*/}
                {/*<Col span={24}>*/}
                  {/*{showDetail? this.state.zt?*/}
                    {/*<Button disabled={this.state.informButton} type="primary" htmlType="submit" loading={formLoading} style={{ marginLeft: 680 }}*/}
                            {/*onClick={() => this.handleSubmit(true)}>重抽</Button>*/}
                    {/*:null*/}
                      {/*:null*/}
                    {/*}*/}
                  {/*<Button onClick={() => this.cancelBack()} style={{ marginLeft: showDetail? this.state.zt?50:710:710 }}>返回</Button>*/}
                {/*</Col>*/}
              {/*</Row>*/}
            {/*</FormItem>*/}
            {/*:null*/}
          {/*}*/}
        </Form>
      </div>
    );
  }
}
